﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Dynamic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using log4net;

namespace Lhn.Ds.Core.Controll
{
    public class BaseModel : INotifyPropertyChanged, IControl
    {
        public static readonly ILog Log =
            LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private IControl _control;
        private bool _isSuspended = true;

        public BaseModel()
        {
            DsContext.InstanceData.IOC.ComposeParts(this);
        }

        public IControl Control
        {
            get => _control;
            set => _control = value;
        }

        public bool IsSuspended => _isSuspended;

        public virtual void Init(object param)
        {
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public virtual void OnActive(ControllEvent e)
        {
            _control?.OnActive(e);
            _isSuspended = false;
        }

        public virtual void OnClosing(ControllEvent e)
        {
            _control?.OnClosing(e);
        }

        public virtual void OnClosed(ControllEvent e)
        {
            _control?.OnClosed(e);
            _isSuspended = false;
        }

        public virtual void OnSuspending(ControllEvent e)
        {
            _control?.OnSuspending(e);
        }

        public virtual void OnSuspended(ControllEvent e)
        {
            _isSuspended = true;
            _control?.OnSuspended(e);
        }

        public virtual void OnAction(string type, object param)
        {
            _control?.OnAction(type, param);
        }

        public void DispatchUI(Action action)
        {
            Application.Current.Dispatcher.Invoke(action);
        }

        public void Dispatch(Action action)
        {
            Task.Factory.StartNew(action.Invoke);
        }
    }
}